package vip.denglei.company.controller;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import vip.denglei.company.util.*;

import java.util.HashMap;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@RestController
public class TestController {
    protected static Logger logger= LoggerFactory.getLogger(TestController.class);


    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public HttpResult test(@RequestBody HashMap map) {

        String message =map.get("msg").toString();
        String response="未获得信息";
        // 连接ChatGPT并获取响应
        try {
             response = connectToChatGPT(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return HttpResult.success(response);
    }
    public String connectToChatGPT(String message) throws IOException {
        // 设置API端点
        String apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";

        // 设置您的OpenAI API密钥
        String apiKey = "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";

        // 创建HTTP客户端
        HttpClient httpClient = HttpClients.createDefault();

        // 创建POST请求
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置请求头
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);

        // 设置请求体
        StringEntity requestEntity = new StringEntity("{\"prompt\": \"" + message + "\", \"max_tokens\": 100}", ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);

        // 发送请求
        HttpResponse response = httpClient.execute(httpPost);

        // 获取响应实体
        HttpEntity entity = response.getEntity();

        // 读取响应内容
        String jsonResponse = EntityUtils.toString(entity);

        return jsonResponse;
    }


}
